import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-06-17
 * Time: 10:33
 */
class Solution8 {

    int left,right,n;
    StringBuilder path;
    List<String> ret;
    public List<String> generateParenthesis(int n1) {
        n = n1;
        path = new StringBuilder();
        ret = new ArrayList<>();

        dfs();
        return ret;
    }

    void dfs() {
        if(right == n) {
            ret.add(path.toString());
            return;
        }

        //添加左括号
        if(left < n) {
            path.append('(');
            left++;
            dfs();
            path.deleteCharAt(path.length()-1);
            left--;
        }

        //添加右括号
        if(right < left) {
            path.append(')');
            right++;
            dfs();
            path.deleteCharAt(path.length()-1);
            right--;
        }
    }
}
